package com.biluo.mvs.utils

import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.util.Log
import android.widget.Toast
import com.biluo.mvs.MvsApplication

object Utils {
	fun showToast(context: Context, tip: String) {
		Toast.makeText(context, tip, Toast.LENGTH_SHORT).show()
	}

	fun showToast(tip: String) {
		Toast.makeText(MvsApplication.instance.getAppContext(), tip, Toast.LENGTH_SHORT).show()
	}

	fun showAlertDialog(context: Context, title: String, msg: String, position: DialogInterface.OnClickListener) {
		AlertDialog.Builder(context).setTitle(title).setMessage(msg)
			.setPositiveButton("确定", position)
			.setNegativeButton("取消", null)
			.create().show()
	}

	fun handleResp(resp: Map<String, Any>, key: String, success: (data: Any?) -> Unit, fail: (msg: String) -> Unit) {
		Log.d(GlobalData.LOG_TAG, "响应结果: $resp")
		if (resp["code"] == null) {
			return fail("网络请求失败")
		}
		var code = (resp["code"] as Double).toInt()
		if (code == 0) {
			success(resp[key])
		} else {
			fail(resp["msg"].toString())
		}
	}

	fun handleResp(resp: Map<String, Any>, success: () -> Unit, fail: (msg: String) -> Unit) {
		Log.d(GlobalData.LOG_TAG, "响应结果: $resp")
		if (resp["code"] == null) {
			return fail("网络请求失败")
		}
		var code = (resp["code"] as Double).toInt()
		if (code == 0) {
			success()
		} else {
			fail(resp["msg"].toString())
		}
	}

	fun handleResp(resp: Map<String, Any>, key: String, success: (data: Any?) -> Unit) {
		handleResp(resp, key, success) {
			showToast(MvsApplication.instance.getAppContext(), it)
		}
	}

	fun handleResp(resp: Map<String, Any>, success: () -> Unit) {
		handleResp(resp, success) {
			showToast(MvsApplication.instance.getAppContext(), it)
		}
	}
}